package com.oracle.service.impl;

import com.oracle.compents.ApiResponse;
import com.oracle.entity.LoginStudent;
import com.oracle.mapper.StudentMapper;
import com.oracle.pojo.Student;
import com.oracle.pojo.Teacher;
import com.oracle.service.LoginStudentService;
import com.oracle.service.LoginTeacherService;
import com.oracle.util.JJWTUtilsStudent;
import com.oracle.util.JJWTUtilsTeacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class LoginStudentServiceImpl implements LoginStudentService {

    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public ApiResponse login(Student student) {
        //通过UsernamePasswordAuthenticationToken获取用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(student.getStuNum(),student.getStuPwd());

        //AuthenticationManager委托机制对authenticationToken 进行用户认证  底层调用StudentDetailsServiceImpl
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没有通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("认证失败");
        }

        //如果认证通过，使用user生成jwt  jwt存入ResponseResult 返回

        //如果认证通过，拿到这个当前登录用户信息
        LoginStudent loginStudent = (LoginStudent) authenticate.getPrincipal();

        //脱敏
        loginStudent.getStudent().setStuPwd(null);


        String stuNum = loginStudent.getStudent().getStuNum();
        System.out.println(stuNum);


        String jwt = JJWTUtilsStudent.getJwtToken(loginStudent.getStudent());

        //把完整的用户信息存入redis  userid为key   用户信息为value
        stringRedisTemplate.opsForValue().set("login:user:"+student.getStuNum(),jwt);
        stringRedisTemplate.expire("login:user:"+student.getStuNum(),3, TimeUnit.HOURS);//设置失效时间
        return ApiResponse.success(jwt);
    }

    @Override
    public void register(Student student) {
        studentMapper.insert(student);
    }

    @Override
    public void loginOut(Student student) {

    }
}
